package pt.ipl.isel.deetc.leic.pdm.g12.yamba;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.TextView;

public class StatusActivity extends BaseActivity implements OnClickListener{
	private static final String TAG = "PDM";
	private Button submit;
	private EditText text;
	private TextView textView;
	private int maxCharsPerMsg; 

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.status);
		submit = (Button) findViewById(R.id.buttonUpdate);
		submit.setOnClickListener(this);		
		
		if (yamba.lastSubmit != null && !yamba.lastSubmit.isEnabled())
			disableSubmit();
		
		yamba.lastSubmit = submit;
		text = (EditText) findViewById(R.id.editText);
		text.addTextChangedListener(mTextEditorWatcher);
		Log.d(TAG, "onCreate");
		
		textView =  (TextView) findViewById(R.id.charsLeft);
		maxCharsPerMsg = Integer.parseInt(yamba.getPreferences().getString("maxCharsMsg", "140"));		
		UpdateCharsLeft(0);		
	}
	
	private void UpdateCharsLeft(int charsWrited)
	{		
		textView.setText(this.getString(R.string.charsLeftStatus, maxCharsPerMsg - charsWrited));		
	}

	/** Called by submit button */
	public void onClick(View v) {
		disableSubmit();
		// Update status and enable submit in background  
		new UpdateStatusTask().execute(text.getText().toString());
		Log.d(TAG, "onClick");
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.removeItem(R.id.status);
		menu.removeItem(R.id.refreshTimeline);
		
		return super.onPrepareOptionsMenu(menu);
	}
	
	public TextWatcher mTextEditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

	
        public void onTextChanged(CharSequence s, int start, int before, int count) {        	        	
			if(s.length() > maxCharsPerMsg) 
        	{        								
        		text.setText((s + "").substring(0, maxCharsPerMsg));        		
        		text.setSelection(maxCharsPerMsg); //posicionar o cursor no fim da mensagem
        		UpdateCharsLeft(maxCharsPerMsg);
        	}
			else
				UpdateCharsLeft(s.length());
        }

		public void afterTextChanged(Editable s) {

		}
	};
	
	// UTILITIES 

	/** Task to update Status and enable submit button (in background) */
	private class UpdateStatusTask extends AsyncTask<String, Void, Void> {
		private volatile Exception error = null;

		protected Void doInBackground(String... params) {
			try {
				((YambaPdmApp)getApplication()).getTwitter().updateStatus(params[0]);
			} catch (Exception ex) { error = ex; }
			
			return null;
		}
		
		protected void onPostExecute(Void res) {
			Log.d(TAG, "onPostExecute");
			if (error != null)
				showToast(getString(R.string.failMessage,error));
			
			enableSubmit();
		}
	}

	/** Displays a Toast with long length duration */ 
	private void showToast(String txt) {
		Toast.makeText(StatusActivity.this, txt, Toast.LENGTH_LONG).show();		
	}

	/** Enable submit button of last activity */
	private void enableSubmit() {
		Button submit = ((YambaPdmApp) getApplication()).lastSubmit;
		submit.setEnabled(true);
		submit.setText(R.string.buttonUpdate);
	}

	/** Disable submit button of this activity */
	private void disableSubmit() {
		submit.setEnabled(false);
		submit.setText(R.string.buttonBusy);
	}
}